package com.outsourcing.bottle;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.gson.Gson;
import com.outsourcing.bottle.db.BottleNetTypeTable;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.db.LanguageConfigTable;
import com.outsourcing.bottle.db.OtherConfigTable;
import com.outsourcing.bottle.domain.BottleNetTypeEntry;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.InitBottleInfo;
import com.outsourcing.bottle.domain.LanguageConfig;
import com.outsourcing.bottle.domain.OtherConfigEntry;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.ui.HomeActivity;
import com.outsourcing.bottle.ui.LoginActivity;
import com.outsourcing.bottle.ui.LoginPlatformActivity;
import com.outsourcing.bottle.ui.LogoFragment;
import com.outsourcing.bottle.util.ActivityManager;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BottlePushService;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.UICore;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.PageIndicator;
/**
 * 
 * @author 06peng
 *
 */
public class SplashActivity extends BasicActivity implements OnClickListener {
	
	private final int new_version = 1;
	private final int initData = 2;
	private final int login = 3;
	private boolean init;
	
	CirclePageFragmentAdapter mAdapter;
	ViewPager mPager;
	PageIndicator mIndicator;
	
	private Button btnHasAccount;
	private Button btnLoginWithOther;
	
	private Handler systemHandler;
	
	private BottleTypeTable btt;
	private BottleNetTypeTable bntt;
	private OtherConfigTable ot;
	private LanguageConfigTable languageTablet;
	private OtherConfigEntry ocEntry;
	
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppContext.setContext(this);
        setContentView(R.layout.splash);
        
        btt = new BottleTypeTable();
        bntt = new BottleNetTypeTable();
        ot = new OtherConfigTable();
        languageTablet = new LanguageConfigTable();
        
        registerSystemHandler();
        initViewpageFragment();
        initWidget();
        networkLocat();
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        AppContext.getInstance().setDeviceId(tm.getDeviceId());
        UICore.getInstance();
        init = getIntent().getBooleanExtra("init", false);
        SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
    	int notice = preferences.getInt("notice", 1);
    	if (notice == 1) {
    		Editor editor = getSharedPreferences(BottlePushService.TAG, MODE_PRIVATE).edit();
	    	editor.putString(BottlePushService.PREF_DEVICE_ID, AppContext.getInstance().getDeviceId());
	    	editor.commit();
			BottlePushService.actionStart(getApplicationContext());		      
    	}
        if (!init) {
			UICore.eventTask(this, this, initData, "", null);
        }
    }
    
    @Override
    public void execute(int mes, Object obj) {
    	switch (mes) {
		case initData:
			initBottleData();
			initedConfig();
			break;
		default:
			break;
		}
    }
    
    /**
     * 初始化组件
     */
    private void initWidget() {
    	btnHasAccount = (Button) findViewById(R.id.splash_has_account);
    	btnHasAccount.setOnClickListener(this);
    	btnLoginWithOther = (Button) findViewById(R.id.splash_login_with_other);
    	btnLoginWithOther.setOnClickListener(this);
    }
    
    private void initViewpageFragment() {
    	 mAdapter = new CirclePageFragmentAdapter(getSupportFragmentManager(), this);
         Bundle bundle = new Bundle();
         bundle.putInt("logo", 0);
         mAdapter.addFragment("", LogoFragment.class, bundle);
         
         Bundle bundle1 = new Bundle();
         bundle1.putInt("logo", 1);
         mAdapter.addFragment("", LogoFragment.class, bundle1);
         
         Bundle bundle2 = new Bundle();
         bundle2.putInt("logo", 2);
         mAdapter.addFragment("", LogoFragment.class, bundle2);
         
         Bundle bundle3 = new Bundle();
         bundle3.putInt("logo", 3);
         mAdapter.addFragment("", LogoFragment.class, bundle3);
         
         Bundle bundle4 = new Bundle();
         bundle4.putInt("logo", 4);
         mAdapter.addFragment("", LogoFragment.class, bundle4);
 		
 		mPager = (ViewPager)findViewById(R.id.pager);
 		mPager.setAdapter(mAdapter);
 		
 		mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
 		mIndicator.setViewPager(mPager);
    }
    
    
    private void initedConfig() {
    	try {
    		String country = getResources().getConfiguration().locale.getCountry();
    		if (country.equals("CN")) {
    			AppContext.setLanguage(1);
    		} else {
    			AppContext.setLanguage(0);
    		}
        	SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
        	int login_uid = preferences.getInt("login_uid", 0);
        	String login_token = preferences.getString("login_token", null);
        	AppContext.getInstance().setLogin_uid(login_uid);
    		AppContext.getInstance().setLogin_token(login_token);
    		
    		String lastVersion = ocEntry.getLast_android_version();
    		String localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    		if (Double.parseDouble(lastVersion) > Double.parseDouble(localVersion)) {
    			Message msg = Message.obtain(systemHandler, new_version, lastVersion);
    			systemHandler.sendMessage(msg);
    		} else {
    			if (login_uid != 0 && login_token != null) {
            		systemHandler.sendEmptyMessage(login);
            	} 
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public static class CirclePageFragmentAdapter extends FragmentPagerAdapter {

    	private Context mContext;
		private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>();
		
		protected static final class FragmentInfo {
            @SuppressWarnings("unused")
			private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            protected  FragmentInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }
    	
		public CirclePageFragmentAdapter(FragmentManager fm, Context context) {
			super(fm);
			this.mContext = context;
		}
		
		public void addFragment(String tag, Class<?> clss, Bundle args) {
			FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args);
			fragments.add(fragmentInfo);
		}

		@Override
		public Fragment getItem(int arg0) {
			FragmentInfo fragmentInfo = fragments.get(arg0);
			return Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args);
		}

		@Override
		public int getCount() {
			return fragments.size();
		}
    }
	
	private void registerSystemHandler() {
		systemHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case login:
					Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
					startActivity(intent);
					finish();
					break;
				case new_version:
					showChoseMes(getString(R.string.new_version_tips) + msg.obj.toString(), 0);
					break;
				default:
					break;
				}
			}
		};
	}
	
	/**
	 * 初始化瓶子配置信息保存到本地
	 */
	private void initBottleData() {
		long time = System.currentTimeMillis();
		System.out.println("begin>>>>>>>>>>>>>>>>" + 0);
		String url = UrlConfig.init_config;
		url += "?sitekey=" + PlatformBindConfig.Sitekey;
		url += "&clitype=2";
		url += "&language=" + AppContext.language;
		try {
			String result = HttpUtils.doGet(url);
			long time1 = System.currentTimeMillis();
			System.out.println("got data by http get>>>>>>>>>>>>>>>>" + (time1 - time));
			ServiceUtils.dout(result);
			Gson gson = new Gson();
			InitBottleInfo bottleInfo = gson.fromJson(result, InitBottleInfo.class);
			long time11 = System.currentTimeMillis();
			System.out.println("parse json data>>>>>>>>>>>>>>>>" + (time11 - time1));
			if (bottleInfo != null) {
				List<BottleTypeEntry> bottleTypes = bottleInfo.getBttypes_list();
				btt.clearTable();
				btt.saveBottleType(bottleTypes);
				long time2 = System.currentTimeMillis();
				System.out.println("save bottle type>>>>>>>>>>>>>>>>" + (time2 - time1));
				bntt.clearTalbe();
				List<BottleNetTypeEntry> bottleNetTypes = bottleInfo.getNettypes_list();
				for (BottleNetTypeEntry bottleNetType : bottleNetTypes) {
					bntt.saveBottleNetType(bottleNetType);
				}
				long time3 = System.currentTimeMillis();
				System.out.println("save bottle net type>>>>>>>>>>>>>>>>" + (time3 - time2));
				ocEntry = bottleInfo.getOther_config();
				ot.clearTable();
				ot.saveBottleOtherConfig(ocEntry);
				LanguageConfig languageConfig = bottleInfo.getLanguage_config();
				languageTablet.clearTable();
				languageTablet.saveBottleLanguageConfig(languageConfig);
				System.out.println("total time>>>>>>>>>>>>>>>>" + (System.currentTimeMillis() - time));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitTips();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private void showExitTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.logout_home));
		builder.setPositiveButton(getString(R.string.confirm_ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ActivityManager.finishAll();
						Process.killProcess(Process.myPid());
						System.exit(0);
					}
				});
		builder.setNegativeButton(getString(R.string.confirm_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.show();
	}

	@Override
	public void onClick(View v) {
		if (v == btnHasAccount) {
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
		} else if (v == btnLoginWithOther) {
			Intent intent = new Intent(this, LoginPlatformActivity.class);
			startActivity(intent);
		}
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		Uri uri = Uri.parse("http://www.mobibottle.com");
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}
	
	@Override
	public void sysMesNegativeButtonEvent(int what) {
		if (AppContext.getInstance().getLogin_uid() != 0 && AppContext.getInstance().getLogin_token() != null) {
    		systemHandler.sendEmptyMessage(login);
    	} 
	}
}